from threading import Thread
from typing import Annotated

from fastapi import APIRouter, Depends

from tasks.task_schedule import start_schedule_task
from choices.choices import TaskType
from schemas.schemas import TaskForecast, TaskSchedule
from tasks.task_forecast import start_forecast_task
from tasks.task_manager import task_manager
from routers.users import oauth2_scheme


tasks_router = APIRouter()


@tasks_router.post("/tasks_forecast")
async def create_task_forecast(
    token: Annotated[str, Depends(oauth2_scheme)],
    task: TaskForecast,
):
    """Создает задачу формирования прогноза."""
    task_manager.add_task(task_name=task.forecast_name, task_type="forecast")
    thread = Thread(
        target=start_forecast_task,
        args=(
            task.statistics_filename,
            task.forecast_name,
        ),
        daemon=True,
    )
    thread.start()
    return {
        "task_type": "forecast",
        "task_name": task.forecast_name,
    }


@tasks_router.post("/tasks_schedule")
async def create_task_schedule(
    token: Annotated[str, Depends(oauth2_scheme)],
    task: TaskSchedule,
):
    """Создает задачу формирования расписания."""
    task_manager.add_task(task_name=task.schedule_name, task_type="schedule")
    thread = Thread(
        target=start_schedule_task,
        args=(
            task.schedule_name,
            task.forecast_id,
            task.date_start_schedule,
        ),
        daemon=True,
    )
    thread.start()
    return {
        "task_type": "schedule",
        "task_name": task.schedule_name,
    }


@tasks_router.get("/tasks")
async def get_task_result(token: Annotated[str, Depends(oauth2_scheme)],
                          task_type: TaskType = TaskType.forecast,
                          ):
    """Возвращает задачи с указанным типом."""
    task_manager.get_data_from_queue()
    return task_manager.task_results(task_type=task_type.value)
